from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import requests
import json
from coach.models.user_models import User
from coach.config.wechat import WECHAT_APPID, WECHAT_SECRET  # 需在config中配置小程序APPID和SECRET

@csrf_exempt
def wechat_login(request):
    """
    小程序登录接口：通过code换取session_key，关联用户信息
    请求参数：code, encryptedData, iv（加密的手机号信息）, avatarUrl（头像URL）
    """
    if request.method != 'POST':
        return JsonResponse({'code': 400, 'msg': '仅支持POST请求'})
    
    data = json.loads(request.body)
    code = data.get('code')
    encrypted_data = data.get('encryptedData')
    iv = data.get('iv')
    avatar_url = data.get('avatarUrl')

    # 1. 调用微信接口获取session_key和openid
    wechat_url = f"https://api.weixin.qq.com/sns/jscode2session?appid={WECHAT_APPID}&secret={WECHAT_SECRET}&js_code={code}&grant_type=authorization_code"
    res = requests.get(wechat_url)
    session_data = res.json()
    if 'errcode' in session_data:
        return JsonResponse({'code': 401, 'msg': f'微信授权失败：{session_data["errmsg"]}'})
    
    openid = session_data['openid']
    session_key = session_data['session_key']

    # 2. 解密手机号（需引入微信解密工具，如pycryptodome）
    # 参考：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
    phone_info = decrypt_phone_number(encrypted_data, session_key, iv)
    phone_number = phone_info.get('purePhoneNumber')

    # 3. 查找或创建用户
    try:
        user = User.objects.get(wechat_openid=openid)
        # 更新头像和手机号
        if avatar_url:
            user.wechat_avatar = avatar_url
        if phone_number:
            user.wechat_phone = phone_number
        user.save()
    except User.DoesNotExist:
        # 新用户默认创建为student角色
        user = User.objects.create(
            username=f'wx_{openid[:8]}',  # 生成唯一用户名
            wechat_openid=openid,
            wechat_avatar=avatar_url,
            wechat_phone=phone_number,
            user_type='student',
            password=''  # 微信登录用户无需密码
        )

    # 4. 返回用户信息（脱敏处理）
    return JsonResponse({
        'code': 200,
        'data': {
            'userId': user.id,
            'username': user.username,
            'avatar': user.wechat_avatar,
            'phone': user.wechat_phone,
            'userType': user.user_type
        }
    })

# 新增解密工具函数（需安装pycryptodome：pip install pycryptodome）
from Crypto.Cipher import AES
import base64

def decrypt_phone_number(encrypted_data, session_key, iv):
    """解密微信手机号加密数据"""
    session_key = base64.b64decode(session_key)
    encrypted_data = base64.b64decode(encrypted_data)
    iv = base64.b64decode(iv)
    
    cipher = AES.new(session_key, AES.MODE_CBC, iv)
    decrypted = cipher.decrypt(encrypted_data)
    # 去除PKCS#7填充
    unpad = lambda s: s[:-ord(s[len(s)-1:])]
    decrypted = unpad(decrypted)
    return json.loads(decrypted.decode('utf-8'))